/**
 * 
 */
package com.ginger.rabbitmq.producer;

import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import com.ginger.rabbitmq.entity.Order;

/**
 * @Description: RabbitMQ 发送
 * @author 姜锋
 * @date 2019年4月2日 上午9:10:41 
 * @version V1.0   
 *
 */
@Component
public class RabbitMQSender {
	
	private final static Logger logger = LoggerFactory.getLogger(RabbitMQSender.class);
	
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	final ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
		@Override
		public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		
			logger.warn("correlationData:"+ correlationData);
			logger.warn("ack:"+ ack);
			if(!ack) {
				logger.warn("投递失败:异常处理---------->");
			}
		}
	};
	
	
	final ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
		@Override
		public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
				String exchange, String routingKey) {
			
			logger.warn("exchange:"+ exchange);
			logger.warn("routingKey:"+ routingKey);
			logger.warn("replyCode:"+ replyCode);
			logger.warn("replyText:"+ replyText);
		}
	};
	
	@SuppressWarnings("rawtypes")
	public void send (Object content, Map<String, Object> properties) throws Exception{
		logger.warn("检测执行content: "+ content);
		MessageHeaders messageHeaders = new MessageHeaders(properties);
		Message message = MessageBuilder.createMessage(content, messageHeaders);
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		//真实环境建议全局唯一ID
		CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
		rabbitTemplate.convertAndSend("spring_exchange2", "springboot.hello", message, correlationData);
	}
	
	public void sendOrder (Order order) throws Exception{
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		//真实环境建议全局唯一ID
		CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
		rabbitTemplate.convertAndSend("spring_exchange2", "springboot.hello", order, correlationData);
	}
	
}
